"use strict";

import Vue from "vue/dist/vue.esm.js";
import Mock from "mockjs";
import io from "socket.io-client";
import ElementUI from "element-ui";
import "../node_modules/element-ui/lib/theme-chalk/index.css";
// import "element-ui/lib/theme-chalk/index.css";
// import selfMoudle from "../src/index.js";
Vue.use(ElementUI);

window.tenv = {
  baseApi: "127.0.0.1:3000",
};
const apiURL = window.tenv.baseApi;

const API = async (url, options) => {
  options.headers = {
    "Content-Type": "application/json",
  };
  return new Promise((resolve, reject) => {
    fetch(url, options)
      .then((res) => res.json())
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
new Vue({
  el: "#app",
  data() {
    return {
      message: "Hello Vue!",
      startFlag: false,
      LSID: "",
      io: null,
      roomInfoList: [],
      roomInfo: {},
    };
  },
  created() {
    this.init();

    this.getRoomList();
  },
  methods: {
    getRandomZhNameByMockJs() {
      const Random = Mock.Random;
      const name = Random.cname();
      return name;
    },
    init() {
      const LSIDName = "LSID";
      const LSID = sessionStorage.getItem(LSIDName);
      if (LSID) {
        this.LSID = LSID;
      } else {
        // 弹框提示要求输入name
        const userName = window.prompt(
          "请输入你的名字",
          this.getRandomZhNameByMockJs()
        );
        // 随机一个10位数值的id
        let NewLSID;
        if (userName) NewLSID = userName;
        else NewLSID = Math.floor(Math.random() * 10000000000);
        this.LSID = NewLSID;
        sessionStorage.setItem(LSIDName, NewLSID);
      }

      const socket = io(apiURL, {
        query: {
          LSID: this.LSID,
        },
      });
      this.io = socket;
      // socket.on("connect", () => {
      //   console.log(`connect`);
      // });
      socket.on("roomInfo", (data) => {
        console.log(`roomInfo data`, data);
        this.roomInfo.userList = data.userList;
      });
      socket.on("leaveRoom", () => {
        console.log(`${this.LSID} leaveRoom disconnect`);
        this.disconnected();
      });
      socket.on("disconnect", () => {
        console.log(`${this.LSID} disconnect`);
        this.disconnected();
      });
      // destory前需要发送disconnected事件
      window.onbeforeunload = () => {
        this.io.emit("disconnect", { LSID: this.LSID });
      };
    },
    apiIsOk(result) {
      return result.data.code === 200;
    },
    disconnected() {
      this.startFlag = false;
      this.roomInfo = {};
      // 刷新页面
      window.location.reload();
    },
    async leaveRoom() {
      // 若是房主则解散房间 否则退出房间
      // const result = await API(`${apiURL}/leaveRoom`, {
      //   method: "POST",
      //   body: JSON.stringify({
      //     LSID: this.LSID,
      //   }),
      // });
      this.io.emit("leaveRoom", { LSID: this.LSID });
      // this.io.on("leaveRoom", (data) => {
      //   console.log(`leaveRoom data`, data);
      //   const isOk = this.apiIsOk(data);
      //   if (isOk) {
      //     this.disconnected();
      //   }
      // });
      // const isOk = this.apiIsOk(result);
      // if (isOk) {
      //   this.startFlag = false;
      //   this.roomInfo = {};
      // }
    },
    async createRoom() {
      const result = await API(`${apiURL}/createRoom`, {
        method: "POST",
        body: JSON.stringify({
          LSID: this.LSID,
        }),
      });
      console.log(`result`, result);
      const isOk = this.apiIsOk(result);
      this.$message({
        message: result.data.msg,
        type: isOk ? "success" : "error",
      });
      if (isOk) {
        this.startFlag = true;
        this.roomInfo = result.data.data;
      }
    },
    async getRoomList() {
      const result = await API(`${apiURL}/getRoomList`, {
        method: "get",
      });
      console.log(`result`, result);
      this.roomInfoList = result.data;
    },
    async joinRoom(roomId) {
      const result = await API(`${apiURL}/joinRoom`, {
        method: "POST",
        body: JSON.stringify({
          LSID: this.LSID,
          roomId,
        }),
      });
      console.log(`result`, result);
      const isOk = this.apiIsOk(result);
      this.$message({
        message: result.data.msg,
        type: isOk ? "success" : "error",
      });
      if (isOk) {
        this.startFlag = true;
        this.roomInfo = result.data.data;
      }
    },
  },
});
